﻿using HomeCloudStorageSystem.DataBase;
using HomeCloudStorageSystem.Dtos;
using HomeCloudStorageSystem.Models;
using System.Collections.Generic;
using System.Linq;

namespace HomeCloudStorageSystem.Services
{
    public class FileUploagLogRepository : IFileUploagLogRepository
    {
        private readonly AppDbContext _context;
        public FileUploagLogRepository(AppDbContext context)
        {
            _context = context;
        }
        public IEnumerable<FileUploagLogAndFileInfosDto> GetFileUploagLogs()
        {
            var result = _context.FileUploagLog
                .Select(n => new FileUploagLogAndFileInfosDto
                {
                    Id = n.Id,
                    UploadPersonnel = n.UploadPersonnel,
                    OperationTime = n.OperationTime,
                    Describe = n.Describe,
                    State = n.State,
                    ConciseFileInfos = (List<ConciseFileInfosDto>)_context.FileInfo.Where(i => i.FileUploagLogId == n.Id).Select(f => new ConciseFileInfosDto
                    {
                        Id = f.Id,
                        FileName = f.FileName,
                        ExtName = f.ExtName,
                    }),
                    Uploader = _context.Users.Where(i => i.Id == n.UploadPersonnel).FirstOrDefault().UserName,
                    HeadImag = _context.Users.FirstOrDefault(i => i.Id == n.UploadPersonnel).HeadImag,
                });
            return result;
        }
        public FileUploagLogAndFileInfosDto GetFileUploagLog(int id)
        {
            var fileUploagLog = _context.FileUploagLog.Where(n => n.Id == id).FirstOrDefault();
            var result = new FileUploagLogAndFileInfosDto
            {
                Id = id,
                UploadPersonnel = fileUploagLog.UploadPersonnel,
                OperationTime = fileUploagLog.OperationTime,
                Describe = fileUploagLog.Describe,
                State = fileUploagLog.State,
                ConciseFileInfos = (List<ConciseFileInfosDto>)_context.FileInfo.Where(i => i.FileUploagLogId == fileUploagLog.Id).Select(f => new ConciseFileInfosDto
                {
                    Id = f.Id,
                    FileName = f.FileName,
                    ExtName = f.ExtName,
                }),
            };
            return result;
        }
        public bool IsExist(int id)
        {
            return _context.FileUploagLog.Any(n => n.Id == id);
        }
    }
}
